package util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Druid工具类
 *
 * @author ZQX
 * @date 2025-02-26
 */
public class DruidUtil {
    /**
     * 数据源对象
     */
    private static DataSource dataSource;

    /**
     * 获取数据源对象
     *
     * @return 数据源对象
     */
    public static DataSource getDataSource() {
        if (dataSource == null) {
            initDataSource();
        }
        return dataSource;
    }

    /**
     * 初始化数据源对象
     */
    private static void initDataSource() {
        Properties prop = new Properties();
        try {
            prop.load(DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 从连接池获取连接对象
     *
     * @return 连接对象
     */
    public static Connection getConnection() {
        try {
            return getDataSource().getConnection();
        } catch (SQLException e) {
            throw new RuntimeException("获取连接对象失败", e);
        }
    }

    /**
     * 关闭连接，回收到连接池
     *
     * @param conn 连接对象
     */
    public static void close(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                System.err.println("关闭数据库连接时发生异常");
            }
        }
    }
}
